from ..base_downloader import *
from ..base_downloader_firefox import BaseDownloaderFirefox
from selenium.webdriver.common.action_chains import ActionChains


class Task41(BaseDownloaderFirefox):
    def login(self):
        username_field = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.ID, "userCode"))
        )
        password_field = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.ID, "password"))
        )
        username_field.send_keys(self.username)
        password_field.send_keys(self.password)
        self.random_sleep(2)

        captcha_input = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.NAME, "code"))
        )
        captcha_solution = solve_captcha_image(self.driver, (By.XPATH, "/html/body/div/div[2]/div/div[2]/form/div[1]/div[3]/div/div[5]/div/div/span/img"))
        if captcha_solution:
            captcha_input.clear()
            captcha_input.send_keys(captcha_solution)

        login_button = WebDriverWait(self.driver, 10).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "button.ant-btn.ant-btn-primary.ant-btn-lg"))
        )
        login_button.click()

        self.random_sleep(0.5)
        self.accept_alert_dialog()
        self.random_sleep(1.5)

    def retrieve_data(self):
        self.click_query_button()
        self.random_sleep(5)    
        self.set_start_and_end_dates()
        self.random_sleep(5)  
        self.click_retrieve_button()

    def click_query_button(self):
        try:
            hiden_menu = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//span[text()='渠道数据管理']"))
            )

            actions = ActionChains(self.driver)
            actions.move_to_element(hiden_menu).perform()
            self.random_sleep(2)

            sales_flow_button = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.XPATH, "//a[contains(text(), '渠道流向明细')]"))
            )

            sales_flow_button.click()

        except Exception as e:
            logger.exception(f"An error occurred while clicking the query button: {e}")

    def set_start_and_end_dates(self):
        start_date_input = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.XPATH, "//input[@placeholder='开始日期']"))
            )
        self.driver.execute_script("arguments[0].value = arguments[1];", start_date_input, self.start_date)

        end_date_input = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//input[@placeholder='结束日期']"))
        )
        self.driver.execute_script("arguments[0].value = arguments[1];", end_date_input, self.end_date)

        self.capture_screenshot()

    def click_retrieve_button(self):
        try:
            retrieve_button = self.driver.find_element(By.XPATH, "//button[span[text()='查询']]")
            retrieve_button.click()
        except Exception as e:
            logger.exception(f"An error occurred while clicking the retrieve button: {e}")

    def export_excel(self):
        self.capture_screenshot()
        self.random_sleep(5)  
        self.driver.find_element(By.XPATH, "//button[span[text()='离线下载']]").click()
        self.random_sleep(5)  
        self.driver.find_element(By.XPATH, "//button[span[text()='确 定']]").click()
        self.random_sleep(5)  
        self.driver.find_element(By.XPATH, "//button[span[text()='查询']]").click() 
        self.random_sleep(20)

        from bs4 import BeautifulSoup
        import requests
        html_content = self.driver.page_source
        soup = BeautifulSoup(html_content, "html.parser")

        download_path = "C:/Users/AZHANG/Downloads" # Need to check with lunde
        path_cells = soup.select("tbody.ant-table-tbody td:nth-child(7) span")
        for cell in path_cells:
            file_path = cell.get("title")
            if file_path:
                file_url = f"https://sjfw.gyao511.com:30005/upload/{file_path}"
                file_response = requests.get(file_url)
                if file_response.status_code == 200:
                    with open(
                        os.path.join(download_path, os.path.basename(file_path)), "wb"
                    ) as f:
                        f.write(file_response.content)
                    print(f"Downloaded: {file_path}")
                else:
                    print(f"Failed to download: {file_path}")

        downloaded_file = self.get_latest_downloaded_file()

        new_file_name = f"{self.site_name}_exported_click_button.xlsx"
        destination_path = os.path.join(self.task_download_dir, new_file_name)

        process_downloaded_file(downloaded_file, destination_path)
        logger.info(f"Processed and saved file to: {destination_path}")

        self.random_sleep(8)
        self.delete_downloaded_files()

    def download_file(self):
        #self.page_html_to_excel()  # One way to download the Excel file
        self.export_excel()        # Another way to download the Excel file; use either method

    def delete_downloaded_files(self):
        """Delete the original downloaded file after processing."""
        try:
            downloaded_file = self.get_latest_downloaded_file()
            if os.path.exists(downloaded_file):
                os.remove(downloaded_file)
                logger.info(f"Deleted original downloaded file: {downloaded_file}")
        except Exception as e:
            logger.error(f"Error deleting downloaded file: {e}")